import React, { useState, useEffect } from 'react';
import { Modal, message, Spin, Tooltip } from 'antd';
import axios from '@/components/service/request.js';
import './index.less';

const FetchImagesText = ({ filePath, visible, onClose }) => {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    if (visible && filePath) {
      setPage(1); // 重置页码
      setImages([]); // 重置图片
      setHasMore(true); // 重置加载状态
      fetchImages(1); // 加载第一页图片
    }
  }, [visible, filePath]);

  const fetchImages = async (page) => {
    setLoading(true);
    try {
      const response = await axios.get('/model/get', { params: { fileName: filePath, page, pageSize: 10 } });
      const newImages = response.data?.map((base64String) => `data:image/png;base64,${base64String}`) || [];
      
      if (response.code === 200) {
        if (newImages.length === 0) {
          setHasMore(false); // 没有更多图片了
        } else {
          setImages((prevImages) => [...prevImages, ...newImages]); // 分批加载
        }
      } else if (response.code === 404) {
        message.error('文件未找到，请检查文件路径');
      } else {
        message.error(`获取图片失败，状态码: ${response.code}`);
      }
    } catch (error) {
      console.error('获取图片失败:', error);
      if (error.response) {
        message.error(`请求失败，状态码: ${error.response.code}`);
      } else {
        message.error('获取图片失败，请检查网络连接');
      }
    } finally {
      setLoading(false);
    }
  };

  const loadMoreImages = () => {
    if (hasMore && !loading) {
      const nextPage = page + 1;
      setPage(nextPage);
      fetchImages(nextPage); // 加载下一页图片
    }
  };
  const handleImageClick = (base64Image) => {
    const byteString = atob(base64Image.split(',')[1]);
    const mimeType = base64Image.split(',')[0].match(/:(.*?);/)[1];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ab], { type: mimeType });
    const blobUrl = URL.createObjectURL(blob);

    window.open(blobUrl, '_blank');
  };
  return (
    <Modal
      title={<div className="modal-header">查看图片</div>}
      visible={visible}
      onCancel={onClose}
      footer={null}
      width={1500}
      className="image-modal"
    >
      {loading && page === 1 ? ( // 仅第一页加载时显示 Spin
        <Spin tip="加载图片中..." />
      ) : (
        <div className="image-grid">
          {images.length > 0 ? (
            images.map((src, index) => (
              <Tooltip key={index} title="点击查看大图">
                <img 
                  src={src} 
                  alt={`模型图片 ${index}`} 
                  loading="lazy" 
                  onClick={() => handleImageClick(src)}
                  style={{ cursor: 'pointer' }}
                />
              </Tooltip>
            ))
          ) : (
            <p>暂无图片</p>
          )}
          {hasMore && !loading && (
            <div className="load-more" onClick={loadMoreImages}>加载更多图片</div>
          )}
        </div>
      )}
    </Modal>
  );
};

export default FetchImagesText;
